import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/entity/home/content/content_data.dart';
import 'package:cbec_app/entity/home/home_data.dart';
import 'package:cbec_app/pages/lottery/view/lottery_result_dialog_widget.dart';
import 'package:cbec_app/pages/signIn/sign_in_result_dialog_widget.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:cbec_app/utils/wechat_mini_program_share_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import '../../../entity/home/navigation_data.dart';
import '../../../entity/lottery/lotter_result_bean.dart';
import '../../../entity/lottery/lottery_bean.dart';
import '../../../entity/lottery/lottery_list_bean.dart';
import '../../../entity/signIn/sign_in_prize_bean.dart';
import '../../../entity/signIn/sign_in_recored_bean.dart';
import '../../lottery/view/SimpleLotteryValue.dart';
import '../../lottery/view/lottery_result_fail_dialog_widget.dart';
import '../../lottery/view/lottery_result_list_widget.dart';

///首页控制器
class SecondaryMicroCtr extends BaseController with SingleGetTickerProviderMixin {
  ///微页面参数
  Map<String, dynamic> microParams = {};

  HomeDataModel? homeDataModel;

  NavigationData? navigation; // 第一个页面 导航数据

  String titleName = '';

  ///装修配置
  List<ContentData> contentComponents = [];

  ///导航装修配置
  Map<String, dynamic> navConfig = {};

  String bgColor = '#FFFFFF';

  //是否登录
  bool isLogin = false;

  ///商品分组id
  String groupId = '';

  ///存储列表id对应的商品信息
  Map<String, List> goodsInfo = {};

  ///存储列表对应的时间戳信息
  Map<String, int> timeStampInfo = {};

  ///导航是否为沉浸式
  bool isImmersionNav = false;

  ///是否显示导航
  bool isShowNav = false;

  late TabController tabCtrLottery;

  late SimpleLotteryController simpleLotteryController;
  List<String> rewardsList = [];
  LotteryBean? lotteryBean;
  LotteryListBean? lotteryListBean;
  LotterResultBean? lotteryResultBean;
  SignInRecoredBean? signInRecoredBean;
  List<SignInPrizeBean?>? signInPrizesListBean;

  @override
  void onInit() async {
    super.onInit();
    print('装修微页面======== ${Get.arguments}');
    microParams = Get.arguments;
    getDecoration();
    EventMgr.on(EventType.refreshMicroIndex, (arg) async {
      logger.e('刷新微页面');
      microParams = arg;
      getDecoration();
      update();
    });

    update();

    UmengCommonSdk.onPageStart('微页面');
  }

  @override
  void onClose() {
    super.onClose();
    UmengCommonSdk.onPageEnd('微页面');
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    getDecoration();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  ///获取装修配置
  void getDecoration() {
    Tools.showLoading();

    Network.getMicroConfig(microParams['id'].toString()).then((value) {
      Tools.hideLoading();
      homeDataModel = HomeDataModel.fromJson(value);
      titleName = homeDataModel?.name ?? '';
      contentComponents = homeDataModel?.content ?? [];
      fetchContentComponentsDataJudgeByType();
      logger.i('content ==== ${contentComponents.toString()}');
      navConfig = value['navigation'];
      isImmersionNav = navConfig['navigationbar_type'] == 'immersion';
      bgColor = value['config']['color'];
      update();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///获取装修配置
  Future getRaffleConfig() {
    return Network.getRaffle().then((value) {
      try {
        if (value != null) {
          logger.i('result ====RaffleConfig ${value}');
          lotteryBean = value;
          rewardsList.clear();
          value?.prizeList?.forEach((v) => {rewardsList..add('${v.image}')});
        }
      } catch (e) {
        logger.e(e);
      }
    }).catchError((onError) {
      logger.i('result ====RaffleConfig ${onError}');
    });
  }

  ///获取装修配置
  requestWin() {
    if (lotteryBean == null || lotteryBean!.num == 0) {
      Tools.showToast('抽奖次数不足');
      return;
    }
    return Network.getRaffleResult().then((value) {
      logger.i('result ==== ${value?.location}');
      lotteryResultBean = value;
      lotteryBean?.num = value?.prizeCount;
      if (value == null || value.location == null || value.storage == 0) {
        showResultFailDialog();
      } else {
        simpleLotteryController.start(target: value?.location ?? 0, duration: Duration(seconds: 3), repeatRound: 3);
        Future.delayed(const Duration(seconds: 3), () => {showResultDialog()});
      }
      update();
    }).catchError((onError) {});
  }

  ///获取装修配置
  Future requestLotteryList() {
    return Network.getRaffleResultList().then((value) {
      logger.i('result ==== ${value}');
      lotteryListBean = value;
      _showResultListDialog();
    }).catchError((onError) {});
  }

  void _showResultListDialog() {
    showDialog(
        context: Get.context!,
        builder: (c) {
          return Dialog(
            child: LotteryResultListWidget(lotteryListBean: lotteryListBean),
          );
        });
  }

  void showResultDialog() {
    showDialog(
        context: Get.context!,
        builder: (c) {
          return Dialog(
            backgroundColor: Colors.transparent,
            child: LotteryResultDialogWidget(
                lotteryResultBean: lotteryResultBean,
                onPress: () {
                  Navigator.pop(Get.context!);
                  requestWin();
                }),
          );
        });
  }

  //失败
  void showResultFailDialog() {
    showDialog(
        context: Get.context!,
        builder: (c) {
          return Dialog(
            backgroundColor: Colors.transparent,
            child: LotteryResultFailDialogWidget(
                lotteryResultBean: lotteryResultBean,
                onPress: () {
                  if (lotteryResultBean != null && lotteryResultBean!.prizeCount != null && lotteryResultBean!.prizeCount! > 0) {
                    requestWin();
                  } else {
                    Tools.showToast('抽奖次数不足');
                  }
                }),
          );
        });
  }

  ///进行签到操作
  Future requestSignInResult() {
    return Network.getSignInResult().then((value) {
      if (value == null) {
        Tools.showToast('签到成功');
        signInRecoredBean = null;
        requestSignInRecord();
      } else {
        signInPrizesListBean = [];
        value.forEach((v) => {print('-----> woolin list = ${v}'), signInPrizesListBean?.add(SignInPrizeBean.fromJson(v))});
        showSignInResultDialog();
      }
    }).catchError((onError) {});
  }

  ///获取签到配置列表
  Future requestSignInRecord() async {
    return Network.getSignInResultRecord().then((value) {
      logger.i('获取签到配置列表result ==== ${value}');
      if (signInRecoredBean == null) {
        signInRecoredBean = value;
        update();
      } else
        signInRecoredBean = value;
    }).catchError((onError) {});
  }

  //签到结果
  void showSignInResultDialog() {
    showDialog(
        context: Get.context!,
        builder: (c) {
          return Dialog(
            insetPadding: EdgeInsets.symmetric(horizontal: 0, vertical: 10),
            backgroundColor: Colors.transparent,
            child: SignInResultDialogWidget(
                prizeList: signInPrizesListBean,
                onPress: () {
                  signInRecoredBean = null;
                  requestSignInRecord();
                }),
          );
        });
  }

  Future getNavSingleDecoration(String id) {
    Tools.showLoading();
    return Network.getMicroConfig(id).then((value) {
      Tools.hideLoading();
      print('单个页面 === $value');
      HomeDataModel homeDataModel = HomeDataModel.fromJson(value);
      if (homeDataModel.mainPage == 1) {
        navigation = homeDataModel.navigation;
      }
      contentComponents = homeDataModel.content ?? [];
      fetchContentComponentsDataJudgeByType();
      update();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  void fetchContentComponentsDataJudgeByType() {
    for (var item in contentComponents) {
      switch (item.type) {
        case 'raffle':
          getRaffleConfig();
          break;
        case 'signin':
          requestSignInRecord();
          break;
        default:
          break;
      }
    }
  }

  // 分享
  void sharePage() {
    WeChatShareUtils.shareMiniProgram(microParams['id'].toString(), 'assets/images/login_logo.png', WeChatShareType.microPage);
  }
}
